package com.jedisdemo;

import redis.clients.jedis.Jedis;

import java.util.Collections;

/**
 * Created by dong peng on 2018/4/22.
 */
public class LockByRedis {

    private static final String LOCK_SUCCESS = "OK";
    private static final Long RELEASE_SUCCESS = 1L;
    private static final String NOT_EXIST = "NX";
    private static final String EXPIRE_TIME = "PX";

    public static boolean getLock(Jedis jedis, String key, String value, long time) {
        String result = jedis.set(key,value, NOT_EXIST,EXPIRE_TIME,time);
        if(LOCK_SUCCESS.equals(result)) {
            return true;
        }else {
            return false;
        }
    }

    public static boolean releaseLock(Jedis jedis, String key, String value) {
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Object result = jedis.eval(script, Collections.singletonList(key), Collections.singletonList(value));

        if (RELEASE_SUCCESS.equals(result)) {
            return true;
        }
        return false;
    }
}
